package com.tgy.admin.Service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tgy.admin.Service.MenuService;
import com.tgy.admin.Service.PermissionService;
import com.tgy.admin.Service.RoleService;
import com.tgy.admin.util.BeanFieldUtils;
import com.tgy.constant.Constant;
import com.tgy.core.service.SysAdminRoleService;
import com.tgy.core.service.SysPermissionService;
import com.tgy.core.service.SysRolePermissionService;
import com.tgy.dTree.Dtree;
import com.tgy.dTree.Status;
import com.tgy.dTree.TreeNode;
import com.tgy.enums.ResponseStatusEnum;
import com.tgy.enums.YesOrNo;
import com.tgy.page.PageQuery;
import com.tgy.pojo.SysPermission;
import com.tgy.result.GraceJSONResult;
import com.tgy.result.LayuiTableResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/6/21 21:04
 *
 * 后台权限业务实现
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private SysPermissionService SysPermissionService;
    @Resource
    private SysAdminRoleService sysAdminRoleService;
    @Resource
    private SysRolePermissionService sysRolePermissionService;
    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private MenuService menuService;
    @Resource
    private RoleService roleService;
    @Resource
    private BeanFieldUtils beanFieldUtils;

    @Override
    public LayuiTableResult getSysPermissionList(SysPermission bo,PageQuery pageQuery) {
        // bo.setAvailable(-1);
        // 查询全部状态的
        pageQuery.setLimit(null);
        bo.setAvailable(null);
        return SysPermissionService.queryLayuiPageList(bo,pageQuery);
    }

    @Override
    public GraceJSONResult updateStatus(String id, Integer status) {
        int i = SysPermissionService.updateStatus(id,status);

        // 更新权限相关信息
        String loginId = StpUtil.getLoginId().toString();
        new Thread(){
            @Override
            public void run() {
                menuService.getMenuAndRoleAndPermission(loginId);
            }
        }.start();

        if (i>0){
            return GraceJSONResult.ok();
        }else {
            return GraceJSONResult.error();
        }
    }

    @Override
    public GraceJSONResult addSysPermission(SysPermission sysPermission) {
        try {
            // 角色名不能重复
            beanFieldUtils.add(sysPermission);
            Boolean aBoolean = SysPermissionService.insertByBo(sysPermission);
            return GraceJSONResult.ok(ResponseStatusEnum.ADD_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.ADD_ERROR);
        }
    }

    @Override
    public GraceJSONResult updateSysPermission(SysPermission sysPermission) {
        try {
            SysPermission sysPermission1 = SysPermissionService.queryById(sysPermission.getId());
            BeanUtil.copyProperties(sysPermission,sysPermission1);
            beanFieldUtils.update(sysPermission1);
            Boolean aBoolean = SysPermissionService.updateByBo(sysPermission1);

            String loginId = StpUtil.getLoginId().toString();
            // 更新权限相关信息
            new Thread(){
                @Override
                public void run() {
                    menuService.getMenuAndRoleAndPermission(loginId);
                }
            }.start();

            return GraceJSONResult.ok(ResponseStatusEnum.UPDATE_SUCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.UPDATE_ERROR);
        }
    }

    @Transactional
    @Override
    public GraceJSONResult delSysPermission(String id) {
        delData(id);
        String loginId = StpUtil.getLoginId().toString();
        // 更新权限相关信息
        new Thread(){
            @Override
            public void run() {
                menuService.getMenuAndRoleAndPermission(loginId);
            }
        }.start();
        return GraceJSONResult.ok(ResponseStatusEnum.DDELETE_SUCESS);
    }

    private void delData(String id){
        // 查询父ID为ID的数据
        SysPermission bo = new SysPermission();
        bo.setPid(id);
        List<SysPermission> permissions = sysPermissionService.queryList(bo);
        if (CollectionUtil.isNotEmpty(permissions)){
            for (SysPermission permission : permissions) {
                delData(permission.getId());
                // 删除数据
                sysPermissionService.deleteById(permission.getId());
                // 删除关联表数据
                List<String> list = new ArrayList<>();
                list.add(permission.getId());
                sysRolePermissionService.deleteByPid(list);
            }
        }
        // 删除数据
        sysPermissionService.deleteById(id);
        // 删除关联表数据
        List<String> list = new ArrayList<>();
        list.add(id);
        sysRolePermissionService.deleteByPid(list);

    }

    @Transactional
    @Override
    public GraceJSONResult delSysPermissionIds(List<String> ids) {
        try {
            Boolean aBoolean = SysPermissionService.deleteWithValidByIds(ids,false);
            // 删除用户关联信息
            sysAdminRoleService.deleteByRid(ids);
            // 删除权限关联信息
            sysRolePermissionService.deleteByPid(ids);
            return GraceJSONResult.ok(ResponseStatusEnum.DDELETE_SUCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.DDELETE_ERROR);
        }
    }

    @Override
    public GraceJSONResult getSysPermissionById(String id) {
        return GraceJSONResult.ok(SysPermissionService.queryById(id));
    }

    @Override
    public Dtree getSysPermission() {
        // 传入一个没有的角色ID即可
        // return roleService.getSysRolePermission("-10000");
        // 查询所有状态为启用的菜单类型数据
        SysPermission permission = new SysPermission();
        permission.setAvailable(YesOrNo.YES.type);
        permission.setCate(Constant.TYPE_MENU);
        List<SysPermission> permissions = sysPermissionService.queryList(permission);

        // 根据pid分组
        Map<String, List<SysPermission>> pidMap = permissions.stream().collect(Collectors.groupingBy(SysPermission::getPid));
        // 获取顶级菜单
        List<TreeNode> treeNodes = getTreeNodes(pidMap, Constant.TYPE_TOP);

        return new Dtree(new Status(),treeNodes);
    }

    private List<TreeNode> getTreeNodes(Map<String, List<SysPermission>> pidMap, String id){
        List<TreeNode> treeNodes = new ArrayList<>();
        List<SysPermission> permissions = pidMap.get(id);
        if (CollectionUtil.isEmpty(permissions)){
            permissions = new ArrayList<>();
        }
        for (SysPermission sysPermission : permissions) {
            TreeNode treeNode = new TreeNode();
            BeanUtil.copyProperties(sysPermission,treeNode);
            String pid = treeNode.getId().toString();
            List<TreeNode> menu = getTreeNodes(pidMap, pid);
            treeNode.setChildren(menu);
            treeNodes.add(treeNode);
        }
        return treeNodes;
    }


}
